import pandas as pd
import numpy as np
# from tensorflow import keras
from keras import layers
from keras import Input
from keras.models import Model
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras import callbacks
from keras.optimizers import adam
from keras.optimizers import RMSprop
callback_list=[
    callbacks.EarlyStopping(monitor="val_loss",patience=500),
    callbacks.ModelCheckpoint(filepath="weather_v2.h5",monitor="val_loss",save_best_only=True),
    callbacks.ReduceLROnPlateau(monitor="val_loss",factor=0.9,verbose=1,patience=10)
]
a_weather=pd.read_csv("weather.csv")
a_train=pd.read_csv("train_std.csv")
a_train=a_train.drop(['Unnamed: 0','Unnamed: 0.1'],axis=1)
del a_weather["Unnamed: 0"]
a_train=np.array(a_train)
a_weather=np.array(a_weather)
window=4
samples=np.zeros((a_train.shape[0]-window,window,a_train.shape[1]))
targets=np.zeros((a_train.shape[0]-window,a_train.shape[1]))
weather_targets=np.zeros((a_train.shape[0]-window,))
xr=0
zt=4
for i in range(samples.shape[0]):
    samples[i]=a_train[xr:xr+4]
    targets[i]=a_weather[zt]
    xr=xr+1 if xr+1<=samples.shape[0]-1 else samples.shape[0]-1
    zt = zt + 1 if xr + 1 <= samples.shape[0] - 1 else samples.shape[0] - 1
samples=samples[:,:,1:]
didital_targets=targets[:,2:7]
weather_targets=targets[:,7:]
print(samples.shape)
print(didital_targets.shape)
print(weather_targets.shape)
weather_targets_onehot=np.zeros((weather_targets.shape[0],7))
for i in range(weather_targets.shape[0]):
    weather_targets_onehot[i][int(weather_targets[i])-1]=1
data_input=Input(shape=(samples.shape[1],samples.shape[-1]))
x=layers.LSTM(128,return_sequences=True,activation="relu")(data_input)
x=BatchNormalization()(x)
x=layers.LSTM(256,return_sequences=False,activation="relu")(x)
x=BatchNormalization()(x)
x=layers.Dense(256,activation="relu")(x)
x=BatchNormalization()(x)
x=layers.Dense(512,activation="tanh")(x)
x=BatchNormalization()(x)
digital_predict=layers.Dense(5,name="digital")(x)
weather_predict=layers.Dense(7,activation="softmax",name="weather")(x)
weather_model=Model(data_input,[digital_predict,weather_predict])
print(weather_model.summary())
weather_model.compile(optimizer=adam(),loss=["mae","categorical_crossentropy"],loss_weights=[5,1],metrics=["accuracy"])
weather_model.fit(samples,[didital_targets,weather_targets_onehot],epochs=10000,batch_size=30,callbacks=callback_list,validation_split=0.3)